<?php
namespace xing\ace\controllersApi;

use xing\ace\models\Menu;
use xing\ace\helper\Tree;
use xing\ace\logic\AdminRuleLogic;
use xing\ace\models\AdminRole;
use xing\ace\models\AdminRule;
use xing\ace\models\ChangeForm;
use xing\ace\models\AdminUser;
use xing\helper\yii\ReturnHelper;
use Yii;
use yii\base\InvalidParamException;
use yii\helpers\ArrayHelper;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use xing\ace\models\LoginForm;
use xing\ace\models\PasswordResetRequestForm;
use xing\ace\models\ResetPasswordForm;
use xing\ace\models\SignupForm;

/**
 * Site controller
 */
class SiteController extends BaseApiController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator']['optional'] = ['login'];  // 不需要认证的action
        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
//        $this->layout = false;
        $menu = AdminRuleLogic::getNav(Yii::$app->user->identity->role_id);
//        $menu = AdminRole::buildNav($menu);
        return $this->returnData($menu);
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->apiLogin()) {
            $user = $model->getUser();
            AdminRuleLogic::$menuKeyMap = [
                'id' => 'id',
                'label' => 'title',
                'url' => 'path',
                '_level' => '_level',
                'items' => 'children',
            ];
            $menu = AdminRuleLogic::getNav($user->role_id);
            return ['user' => $user, 'menu' => $menu];
        } else {
            return $this->error(implode(',', $model->getFirstErrors()));
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->returnApiSuccess();
    }


    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                return $this->returnApiSuccess();
            } else {
                return $this->error('Sorry, we are unable to reset password for the provided email address.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            return $this->returnApiSuccess();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    public function actionChangePass()
    {
        $model = new ChangeForm();
        if($model->load(Yii::$app->request->post()))
        {
            $user = AdminUser::getByPK(Yii::$app->user->id);
            if((md5($model->original) === $user->password))
            {
                if($model->validate())
                {
                    $user->password = md5($model->password);
                    if($user->save())
                        return $this->returnApiSuccess();
                }
            }
            else
                $model->addError('original', '原密码错误');
        }

        return $this->render('change', ['model'=>$model]);
    }
}
